#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <iostream>

void Usage(char *process)
{
    std::cout << std::endl
    << " Usage: " << process << " + ip + port" << std::endl
    << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(-1);
    }

    int sockid = socket(AF_INET, SOCK_STREAM, 0);
    //std::string ip = "121.37.203.247";
    //uint16_t port = 8080;

    sockaddr_in net;
    bzero(&net, sizeof(net));
    net.sin_family = AF_INET;
    net.sin_port = htons(atoi(argv[2]));
    char NetBuf[16];
    inet_pton(AF_INET, argv[1], &net.sin_addr);

    int n = connect(sockid, (const struct sockaddr *)&net, sizeof(net));
    if (n < 0)
    {
        exit(-1);
    }

    std::string send;
    while (1)
    {
        std::cout << "Please input: ";
        getline(std::cin, send);
        write(sockid, send.c_str(), send.size());

        char buffer[1024];
        int n = read(sockid, buffer, sizeof(buffer) - 1);

        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}